//
//  WNHomePictureView.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/28.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let ItemMargin : CGFloat = 5

private let ItemWidth = (ScreenWidth - WNCellMargin - 2 * ItemMargin) / 3

class WNHomePictureView: UICollectionView {

    var picUrls : [WNHomePicture]?{
        
        didSet {
            
            messageLabel.text = "\(picUrls?.count ?? 0)"
            //  根据图片的个数计算大小，更新配图大小约束
            calcSize(count: picUrls!.count )
            //  数据源发生改变，重新加载数据
            self.reloadData()

            
        }
    }
    
    fileprivate lazy var messageLabel : UILabel = {
        
        let label = UILabel(fontSize: 20, textColor: UIColor.purple)
        
        return label
    }()
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        
        flowLayout.minimumLineSpacing = ItemMargin
        
        flowLayout.minimumInteritemSpacing = ItemMargin
        
        super.init(frame: frame, collectionViewLayout:
            flowLayout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        register(HMHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewCellIdentifier)
        
        dataSource = self
        
        addSubview(messageLabel)
        
        messageLabel.snp.makeConstraints { (make) in
            
            make.center.equalTo(self)
        }
    }
    
    //根据个数计算配图尺寸
    private func calcSize(count : Int){
        
        if count == 1 {
            
            //下载图片后将cell尺寸设为图片大小
            let imageUrl = picUrls?.first?.thumbnail_pic
            
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl){
                
                var imageSize = localImage.size
                
                if imageSize.width < 80 {
                    
                    let imageWidth : CGFloat = 80
                    
                    //  图片的高度
                    var imageHeight = imageWidth / localImage.size.width * localImage.size.height
                
                    imageHeight = imageHeight > 150 ? 150 : imageHeight
                    
                    imageSize = CGSize(width: imageWidth, height: imageHeight)

                }
                
                self.snp.updateConstraints({ (make) in
                    
                    make.size.equalTo(imageSize).priority(.high)
                    
                })
                
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                
                flowLayout.itemSize = imageSize
                
            }
            return
        }
        
        //列
        let cols = count > 3 ? 3 : count
        //行数
        let rows = (count - 1) / 3 + 1
        
        //  计算宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //  计算高度
        let pictureViewHeight = CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(CGSize(width: pictureViewWidth, height: pictureViewHeight)).priority(.high)
        }
        
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
    }
}


    //  MARK: --实现UICollectionViewDataSource
    extension WNHomePictureView:UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return picUrls?.count ?? 0
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewCellIdentifier, for: indexPath) as! HMHomePictureViewCell
            //  设置图片模型
            cell.homePic = picUrls![indexPath.item]
            
            return cell
        }
        
    }
    
    //  自定义首页配图cell
    class HMHomePictureViewCell: UICollectionViewCell {
        //  MARK: --   懒加载控件
        fileprivate lazy var imageView: UIImageView = {
            let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
            //  按照图片原始比例等比显示
            imageView.contentMode = .scaleAspectFill
            //  裁剪超出部分
            imageView.clipsToBounds = true
            return imageView
        }()
        
        //  模型数据
        var homePic: WNHomePicture? {
            didSet {
                
                if let urlStr = homePic?.thumbnail_pic {
                    imageView.sd_setImage(with: URL(string: urlStr), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                }
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        //  添加控件设置约束
        fileprivate func setupUI() {
            contentView.addSubview(imageView)
            imageView.snp.makeConstraints { (make) in
                make.edges.equalTo(contentView)
            }
        }
        
    }
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

